const { append } = require("express/lib/response");
const jwt = require("jsonwebtoken");
var jwtScrect = "ComprehensiveCurriculumDesign"; //签名

/* 模块用于设置token，获取token */
//登录接口 生成token的方法
exports.setToken = async (user_name, password) => {
	try {
		return await new Promise((resolve, reject) => {
			//expiresln 设置token过期的时间
			const token = jwt.sign(
				{ user_name, password },
				jwtScrect,
				{
					expiresIn: "24h",
				},
				(err, token) => {
					if (err) reject();
					console.log("token:", token);
					resolve(token);
				}
			);
		});
	} catch (err_1) {
		console.log(err_1);
	}
};

//各个接口需要验证token的方法
exports.getToken = async (token) => {
	try {
		return await new Promise((resolve, reject) => {
			if (!token) {
				console.log("Token is null!");
				reject({
					error: "Token is null!",
				});
			} else {
				var info = jwt.verify(token.split(" ")[1], jwtScrect);
				console.log(info);
				resolve(info); //解析返回的值（sign 传入的值）
			}
		});
	} catch (err) {
		console.log(err);
	}
};
